import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:get_storage/get_storage.dart';
import 'package:learning/generated/LocalModel.dart';
import 'package:learning/pages/MyHomePage.dart';
import 'package:learning/pages/SelectedAttrebute.dart';
import 'package:learning/pages/exam/CategoryPage.dart';
import 'package:learning/pages/exam/ExamResultPage.dart';
import 'package:learning/pages/exam/MainExamPage.dart';
import 'package:provider/provider.dart';

import 'generated/l10n.dart';

void main() async {
  await GetStorage.init();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    BrnInitializer.register(
        allThemeConfig: BrnAllThemeConfig(
            commonConfig: BrnCommonConfig(brandPrimary: Colors.blue)));
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.white,
      statusBarBrightness: Brightness.dark,
    ));
    final box = GetStorage();
    int categoryId = box.hasData("categoryId") ? box.read("categoryId") : 0;
    if (categoryId == 0) {
      Navigator.pushNamed(context, "/selected");
    }

    // LocalModel localModel=new LocalModel();
    //S.load(const Locale('zh','CN'));
    return MultiProvider(
        providers: [
          ChangeNotifierProvider<LocalModel>(create: (_) => LocalModel()),
        ],
        child: Consumer<LocalModel>(builder: (context, localModel, child) {
          print("LocalModel2");
          print("---${localModel.getLocale()}");
          return MaterialApp(
            title: 'Flutter Demo',
            supportedLocales: S.delegate.supportedLocales,
            localizationsDelegates: const [
              GlobalMaterialLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,
              S.delegate
            ],
            locale: localModel.getLocale(),
            localeResolutionCallback:
                (Locale? locale, Iterable<Locale> supportedLocales) {
              print("localeResolutionCallback `${locale}`");
              print("localeResolutionCallback: `${localModel.getLocale()}`");
              // 重置语言选项
              // Provider.of<LocalModel>(context, listen: false).local(locale??const Locale('zh','UG'));
              if (localModel.getLocale().countryCode == 'CN') {
                return Locale('zh', 'CN');
              } else {
                return Locale('zh', 'UG');
              }
            },
            theme: ThemeData(
              primarySwatch: Colors.blue,
              appBarTheme: AppBarTheme(
                  backgroundColor: Colors.blue,
                  elevation: 0,
                  foregroundColor: Colors.blue),

              // This is the theme of your application.
              //
              // Try running your application with "flutter run". You'll see the
              // application has a blue toolbar. Then, without quitting the app, try
              // changing the primarySwatch below to Colors.green and then invoke
              // "hot reload" (press "r" in the console where you ran "flutter run",
              // or simply save your changes to "hot reload" in a Flutter-supported
              // 3.系统语言改变回调事件

              dividerColor: Colors.blue,
              // This is the theme of your application.
              //
              // TRY THIS: Try running your application with "flutter run". You'll see
              // the application has a blue toolbar. Then, without quitting the app,
              // try changing the seedColor in the colorScheme below to Colors.green
              // and then invoke "hot reload" (save your changes or press the "hot
              // reload" button in a Flutter-supported IDE, or press "r" if you used
              // the command line to start the app).
              //
              // Notice that the counter didn't reset back to zero; the application
              // state is not lost during the reload. To reset the state, use hot
              // restart instead.
              //
              // This works for code too, not just values: Most code changes can be
              // tested with just a hot reload.
              colorScheme: ColorScheme.light(),
              useMaterial3: true,
            ),
            //  home: getBuild(MyHomePage(),localModel),
            onGenerateRoute: (route) {
              print("route.name:${route.name}");
              switch (route.name) {
                case '/selected':
                  return getBuild(SelectedAttrebute(), localModel);
                case '/mainexam':
                  return getBuild(
                      MainExamPage(arguments: route.arguments), localModel);
                case '/mainexamresult':
                  return getBuild(
                      ExamResultPage(arguments: route.arguments), localModel);
                case '/maincategory':
                  return getBuild(
                      CategoryPage(arguments: route.arguments), localModel);
                default:
                  return getBuild(MyHomePage(), localModel);
              }
            },
            /*  routes: {
              '/': (context) =>getBuild(MyHomePage(),localModel),
              '/selected': (context) =>getBuild(SelectedAttrebute(),localModel),
             '/mainexam': (context) =>getBuild(MainExamPage(),localModel), // 选中页面
            },*/
          );
        }));
  }

  MaterialPageRoute getBuild(Widget widget, LocalModel localModel) {
    return MaterialPageRoute(
        builder: (context) => Directionality(
            textDirection: getDirection(localModel.getLocale()),
            // use this
            child: widget
            // set it to rtl

            ));
  }

  bool isDirectionRTL(BuildContext context) {
    return S.of(context).dir == 'rtl';
  }
}

isDirectionRTLL(BuildContext context) {
  return S.of(context).dir == 'rtl';
}

TextDirection getDirection(Locale context) {
  switch (context.countryCode) {
    case 'UG':
      return TextDirection.rtl;
    case 'CN':
      return TextDirection.ltr;
    default:
      return TextDirection.ltr;
  }
}
